using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace NIH.SharePoint.Branding.Features.SP2013Branding
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("068bea4f-6503-42ea-ba18-2da63f1473c6")]
    public class SP2013BrandingEventReceiver : SPFeatureReceiver
    {
        //private static string NIH_DFLT_MASTERPAGE = "_catalogs/masterpage/NIHdefaultV4.master";
        private static string NIH_DFLT_MASTERPAGE = "_catalogs/masterpage/NIHseattle.master";
        private static string NIH_MPS_MASTERPAGE = "_catalogs/masterpage/NIHmwsdefaultv4.master";
        private static string NIH_SITE_LOGO = "SiteAssets/SP2013Branding/Images/banner_bldg1.png";
        //private static string NIH_SITE_LOGO = "SiteAssets/SP2013Branding/Images/logo_nih.gif";
        private static string MOSS_SITE_LOGO = "/_layouts/images/siteIcon.png";
        //private static string MOSS_DFLT_MASTERPAGE = "_catalogs/masterpage/v4.master";
        private static string MOSS_DFLT_MASTERPAGE = "_catalogs/masterpage/seattle.master";
        private static string MOSS_MPS_MASTERPAGE = "_catalogs/masterpage/mwsdefaultv4.master";
        //private static string MOSS_MPS_MASTERPAGE = "_catalogs/masterpage/seattle.master";
        private static string WEB_PROP_ORIG_MASTERURL = "OriginalMasterURL";
        private static string WEB_PROP_ORIG_CUSTOM_MASTERURL = "OriginalCustomMasterURL";
        private static string WEB_PROP_INHERIT_CUSTOM_MASTERURL = "__InheritsCustomMasterUrl";
        private static string WEB_FEATURE_DEFID = "0f486454-f97e-4273-9f46-e8b20e431b7a";

        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            if (web != null)
            {
                SetMasterPage(web);
            }
        }

        private static void SetMasterPage(SPWeb web)
        {
            try
            {
                bool isInherited = false;
                SPFile customMasterFile = null;
                SPCustomizedPageStatus customMasterFileStatus = SPCustomizedPageStatus.None;

                if (web.AllProperties.ContainsKey(WEB_PROP_INHERIT_CUSTOM_MASTERURL))
                {
                    if ("True".Equals(web.AllProperties[WEB_PROP_INHERIT_CUSTOM_MASTERURL]))
                    {
                        isInherited = true;
                    }
                }
                if (!isInherited)
                {
                    if (web.CustomMasterUrl != null)
                    {
                        try
                        {
                            customMasterFile = web.GetFile(web.CustomMasterUrl);
                            if (customMasterFile != null)
                            {
                                customMasterFileStatus = customMasterFile.CustomizedPageStatus;
                            }
                        }
                        catch (ArgumentException)
                        {
                            throw new Exception(string.Format("Encountered Exception in SPWeb.GetFile() in Web [{0}]", web.ServerRelativeUrl));
                        }
                    }
                }
                if (isInherited || customMasterFileStatus == SPCustomizedPageStatus.Uncustomized)
                {
                    //activate feature in subsite.
                    if (!web.Properties.ContainsKey(WEB_PROP_ORIG_CUSTOM_MASTERURL))
                    {
                        // Save current settings of MasterUrl and CustomMasterUrl
                        web.Properties[WEB_PROP_ORIG_MASTERURL] = web.MasterUrl;
                        web.Properties[WEB_PROP_ORIG_CUSTOM_MASTERURL] = web.CustomMasterUrl;
                        web.Properties.Update();
                    }
                    string webAppRelativePath = web.ServerRelativeUrl;
                    if (!webAppRelativePath.EndsWith("/"))
                    {
                        webAppRelativePath += "/";
                    }
                    ///
                    /// If the template is MPS (meeting site), then apply the MasterUrl and CustomMasterUrl here.
                    ///

                    if (web.WebTemplate == "MPS")
                    {
                        web.CustomMasterUrl = webAppRelativePath + NIH_MPS_MASTERPAGE;
                        web.MasterUrl = webAppRelativePath + NIH_MPS_MASTERPAGE;
                        //web.SiteLogoUrl = (web.Site.Url.EndsWith("/") ? web.Site.Url : web.Site.Url + "/") + NIH_SITE_LOGO;
                        //oWeb.UIVersion = 4; // Use newser version of UI
                        web.Update();
                    }
                    else
                    {
                        web.CustomMasterUrl = webAppRelativePath + NIH_DFLT_MASTERPAGE;
                        web.MasterUrl = webAppRelativePath + NIH_DFLT_MASTERPAGE;
                        //web.SiteLogoUrl = (web.Site.Url.EndsWith("/") ? web.Site.Url : web.Site.Url + "/") + NIH_SITE_LOGO;
                        //oWeb.UIVersion = 4; // Use newser version of UI
                        web.Update();
                    }
                }

                if (web.Webs.Count > 0)
                {
                    foreach (SPWeb subWeb in web.Webs)
                    {
                        activateFeature(subWeb);
                    }
                }
            }
            catch (Exception e)
            {
                if (web != null)
                {
                    throw new Exception(string.Format("Encountered Exception applying NIH Master Page in Web: [{0}]", web.ServerRelativeUrl + e.Message));
                }
            }
        }
        /// <summary>
        /// Activate the feature in subsites
        /// </summary>
        /// <param name="thisWeb"></param>
        private static void activateFeature(SPWeb thisWeb)
        {
            bool featureExists = false;
            using (thisWeb)
            {
                foreach (SPFeature feature in thisWeb.Features)
                {
                    if (feature.DefinitionId.Equals(new Guid(WEB_FEATURE_DEFID)))
                    {
                        featureExists = true;
                    }
                }
            }
            if (!featureExists)
            {
                thisWeb.Features.Add(new Guid(WEB_FEATURE_DEFID), true);
                thisWeb.Update();
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb site = properties.Feature.Parent as SPWeb;
            if (site != null)
            {
                // Calculate relative path of site from Web Application root.
                UnsetMasterPage(site);
            }
        }

        /// <summary>
        /// Reset the master pages to its original property values.
        /// </summary>
        /// <param name="oWeb"></param>
        private static void UnsetMasterPage(SPWeb oWeb)
        {
            if (oWeb.Properties.ContainsKey(WEB_PROP_ORIG_MASTERURL))
            {
                SPWeb rootWeb = oWeb.Site.RootWeb;
                string webAppRelativePath = oWeb.ServerRelativeUrl;
                if (!webAppRelativePath.EndsWith("/"))
                {
                    webAppRelativePath += "/";
                }
                if (oWeb.WebTemplate == SPWebTemplate.WebTemplateMWS)
                {
                    oWeb.CustomMasterUrl = webAppRelativePath + MOSS_MPS_MASTERPAGE;
                    oWeb.MasterUrl = webAppRelativePath + MOSS_MPS_MASTERPAGE;
                    //oWeb.SiteLogoUrl = MOSS_SITE_LOGO;
                    oWeb.Update();
                }
                else
                {
                    oWeb.CustomMasterUrl = webAppRelativePath + MOSS_DFLT_MASTERPAGE;
                    oWeb.MasterUrl = webAppRelativePath + MOSS_DFLT_MASTERPAGE;
                    //oWeb.SiteLogoUrl = MOSS_SITE_LOGO;
                    oWeb.Update();
                }
            }

            if (oWeb.Webs.Count > 0)
            {
                foreach (SPWeb web in oWeb.Webs)
                {
                    deActivateFeature(web);
                }
            }
        }
        /// <summary>
        /// Deactivate the feature in subsites
        /// </summary>
        /// <param name="thisWeb"></param>
        private static void deActivateFeature(SPWeb thisWeb)
        {
            bool featureExists = false;
            using (thisWeb)
            {
                foreach (SPFeature feature in thisWeb.Features)
                {
                    if (feature.DefinitionId.Equals(new Guid(WEB_FEATURE_DEFID)))
                    {
                        featureExists = true;
                    }
                }
            }
            if (featureExists)
            {
                thisWeb.Features.Remove(new Guid(WEB_FEATURE_DEFID));
                thisWeb.Update();
            }
        }
    }
}
